package mya.mes.mdc.logic.alarm.mqtt;

import mya.common.jpa.context.NoLoginLogic;
import mya.common.jpa.context.ServiceContext;
import mya.common.util.Utils;
import mya.mes.mdc.local.alarm.AlarmService;
import mya.mes.mdc.local.alarm.MdcAlarmResult;
import mya.mes.mdc.logic.alarm.build.AlarmServiceImpl;
import mya.mes.mdc.logic.dispatch.executor.DispatchExecutor;
import mya.mes.mdc.share.plc.PlcTagVoProcessor;
import mya.mes.mdc.share.vo.plc.PlcTagVo;

import java.util.List;

public class MqttAlarmProcessor implements PlcTagVoProcessor<MdcAlarmResult> {

    final Long zoneId;

    private final AlarmService alarmService;

    public MqttAlarmProcessor(final Long zoneId) {
        this.zoneId = zoneId;
        this.alarmService = new AlarmServiceImpl(zoneId);
    }

    @Override
    public String getId() {
        return "MQTT_ALARM_PROCESS_DEFAULT";
    }

    @Override
    public MdcAlarmResult process(Long mqttMsgId, List<PlcTagVo> alarmVoList) throws Exception {
        if (Utils.isNullOrEmpty(alarmVoList)) {
            return null;
        }
        MdcAlarmResult alarmResult = alarmProcess(alarmVoList);
        if (alarmResult != null && alarmResult.dispatchContent != null) {
            DispatchExecutor.getInstance().queueDispatch(alarmResult.dispatchContent);
        }
        return alarmResult;
    }


    private MdcAlarmResult alarmProcess(List<PlcTagVo> voList) throws Exception {
        NoLoginLogic logic = new NoLoginLogic("0") {
            @Override
            protected Object process(ServiceContext context) throws Exception {
                return alarmService.processAlarm(context, voList);
            }
        };
        try {
            return (MdcAlarmResult) logic.callLogic();
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

}
